// pages/listening/listening.js
const wordsData = {
  "animals": [
    {"word": "cat", "chinese": "猫", "image": "/images/words/cat.png", "sound": "/sounds/word-cat.mp3"},
    {"word": "dog", "chinese": "狗", "image": "/images/words/dog.png", "sound": "/sounds/word-dog.mp3"},
    {"word": "bird", "chinese": "鸟", "image": "/images/words/bird.png", "sound": "/sounds/word-bird.mp3"},
    {"word": "fish", "chinese": "鱼", "image": "/images/words/fish.png", "sound": "/sounds/word-fish.mp3"},
    {"word": "rabbit", "chinese": "兔子", "image": "/images/words/rabbit.png", "sound": "/sounds/word-rabbit.mp3"},
    {"word": "tiger", "chinese": "老虎", "image": "/images/words/tiger.png", "sound": "/sounds/word-tiger.mp3"},
    {"word": "lion", "chinese": "狮子", "image": "/images/words/lion.png", "sound": "/sounds/word-lion.mp3"},
    {"word": "elephant", "chinese": "大象", "image": "/images/words/elephant.png", "sound": "/sounds/word-elephant.mp3"}
  ],
  "fruits": [
    {"word": "apple", "chinese": "苹果", "image": "/images/words/apple.png", "sound": "/sounds/word-apple.mp3"},
    {"word": "banana", "chinese": "香蕉", "image": "/images/words/banana.png", "sound": "/sounds/word-banana.mp3"},
    {"word": "orange", "chinese": "橙子", "image": "/images/words/orange.png", "sound": "/sounds/word-orange.mp3"},
    {"word": "grape", "chinese": "葡萄", "image": "/images/words/grape.png", "sound": "/sounds/word-grape.mp3"},
    {"word": "strawberry", "chinese": "草莓", "image": "/images/words/strawberry.png", "sound": "/sounds/word-strawberry.mp3"},
    {"word": "watermelon", "chinese": "西瓜", "image": "/images/words/watermelon.png", "sound": "/sounds/word-watermelon.mp3"},
    {"word": "pear", "chinese": "梨", "image": "/images/words/pear.png", "sound": "/sounds/word-pear.mp3"},
    {"word": "peach", "chinese": "桃子", "image": "/images/words/peach.png", "sound": "/sounds/word-peach.mp3"}
  ],
  "colors": [
    {"word": "red", "chinese": "红色", "image": "/images/words/red.png", "sound": "/sounds/word-red.mp3"},
    {"word": "blue", "chinese": "蓝色", "image": "/images/words/blue.png", "sound": "/sounds/word-blue.mp3"},
    {"word": "green", "chinese": "绿色", "image": "/images/words/green.png", "sound": "/sounds/word-green.mp3"},
    {"word": "yellow", "chinese": "黄色", "image": "/images/words/yellow.png", "sound": "/sounds/word-yellow.mp3"},
    {"word": "orange", "chinese": "橙色", "image": "/images/words/orange-color.png", "sound": "/sounds/word-orange.mp3"},
    {"word": "purple", "chinese": "紫色", "image": "/images/words/purple.png", "sound": "/sounds/word-purple.mp3"},
    {"word": "pink", "chinese": "粉色", "image": "/images/words/pink.png", "sound": "/sounds/word-pink.mp3"},
    {"word": "black", "chinese": "黑色", "image": "/images/words/black.png", "sound": "/sounds/word-black.mp3"}
  ],
  "numbers": [
    {"word": "one", "chinese": "一", "image": "/images/words/one.png", "sound": "/sounds/word-one.mp3"},
    {"word": "two", "chinese": "二", "image": "/images/words/two.png", "sound": "/sounds/word-two.mp3"},
    {"word": "three", "chinese": "三", "image": "/images/words/three.png", "sound": "/sounds/word-three.mp3"},
    {"word": "four", "chinese": "四", "image": "/images/words/four.png", "sound": "/sounds/word-four.mp3"},
    {"word": "five", "chinese": "五", "image": "/images/words/five.png", "sound": "/sounds/word-five.mp3"},
    {"word": "six", "chinese": "六", "image": "/images/words/six.png", "sound": "/sounds/word-six.mp3"},
    {"word": "seven", "chinese": "七", "image": "/images/words/seven.png", "sound": "/sounds/word-seven.mp3"},
    {"word": "eight", "chinese": "八", "image": "/images/words/eight.png", "sound": "/sounds/word-eight.mp3"},
    {"word": "nine", "chinese": "九", "image": "/images/words/nine.png", "sound": "/sounds/word-nine.mp3"},
    {"word": "ten", "chinese": "十", "image": "/images/words/ten.png", "sound": "/sounds/word-ten.mp3"}
  ]
};

Page({
  data: {
    allWords: [],
    currentQuestion: null,
    currentQuestionIndex: 0,
    options: [],
    currentSound: '',
    isPlaying: false,
    hasAnswered: false,
    showScore: false,
    correctCount: 0,
    totalCount: 0,
    scoreRate: 0,
    audioContext: null
  },

  onLoad() {
    // 创建音频上下文
    this.audioContext = wx.createInnerAudioContext();
    this.audioContext.onEnded(() => {
      this.setData({
        isPlaying: false
      });
    });
    
    // 初始化题目
    this.initWords();
  },

  onShow() {
    // 每次显示页面时重新打乱题目
    this.initWords();
  },

  initWords() {
    // 合并所有分类的单词
    const allWords = [];
    Object.keys(wordsData).forEach(category => {
      allWords.push(...wordsData[category]);
    });
    
    // 每次重新打乱
    this.setData({
      allWords: this.shuffleArray([...allWords]),
      currentQuestionIndex: 0,
      correctCount: 0,
      totalCount: 0,
      scoreRate: 0,
      hasAnswered: false,
      showScore: false
    });
    
    // 开始第一题
    this.startNewQuestion();
  },

  onUnload() {
    if (this.audioContext) {
      this.audioContext.destroy();
    }
  },

  // 打乱数组
  shuffleArray(array) {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
  },

  // 开始新题目
  startNewQuestion() {
    if (this.data.currentQuestionIndex >= this.data.allWords.length) {
      // 所有题目完成，显示统计
      this.showFinalScore();
      return;
    }

    const correctWord = this.data.allWords[this.data.currentQuestionIndex];
    
    // 生成选项（1个正确答案 + 3个干扰项）
    const wrongOptions = this.data.allWords
      .filter(word => word.word !== correctWord.word)
      .slice(0, 3);
    
    // 合并选项并打乱顺序（注意：shuffleArray 返回新数组）
    let options = [correctWord, ...wrongOptions];
    options = this.shuffleArray(options);
    
    // 标记正确答案
    const optionsWithFlag = options.map((word, index) => ({
      ...word,
      isCorrect: word.word === correctWord.word,
      selected: false,
      disabled: false
    }));

    this.setData({
      currentQuestion: correctWord,
      options: optionsWithFlag,
      currentSound: correctWord.sound,
      isPlaying: false,
      hasAnswered: false
    });
  },

  // 播放发音
  playSound() {
    if (this.data.hasAnswered) return;
    
    if (this.audioContext) {
      this.audioContext.src = this.data.currentSound;
      this.audioContext.play();
      this.setData({
        isPlaying: true
      });
    }
  },

  // 选择选项
  selectOption(e) {
    if (this.data.hasAnswered) return;
    
    const index = e.currentTarget.dataset.index;
    const options = [...this.data.options];
    const selectedOption = options[index];
    
    // 标记已选择
    options.forEach((opt, i) => {
      opt.selected = i === index;
      opt.disabled = true;
    });
    
    const isCorrect = selectedOption.isCorrect;
    
    // 更新记录
    const app = getApp();
    app.updateRecords('listening', isCorrect);
    
    // 更新统计
    const correctCount = this.data.correctCount + (isCorrect ? 1 : 0);
    const totalCount = this.data.totalCount + 1;
    const scoreRate = totalCount > 0 ? ((correctCount / totalCount) * 100).toFixed(1) : 0;
    
    this.setData({
      options,
      hasAnswered: true,
      correctCount,
      totalCount,
      scoreRate
    });
  },

  // 下一题
  nextQuestion() {
    const nextIndex = this.data.currentQuestionIndex + 1;
    this.setData({
      currentQuestionIndex: nextIndex
    });
    this.startNewQuestion();
  },

  // 重新开始
  restartGame() {
    // 重新打乱单词
    this.setData({
      allWords: this.shuffleArray([...this.data.allWords]),
      currentQuestionIndex: 0,
      correctCount: 0,
      totalCount: 0,
      scoreRate: 0,
      showScore: false
    });
    this.startNewQuestion();
  },

  // 显示最终得分
  showFinalScore() {
    this.setData({
      showScore: true,
      currentQuestion: null,
      options: []
    });
  },

  onAudioEnd() {
    this.setData({
      isPlaying: false
    });
  }
});

